#include "ServerCore.h"

ServerCore::ServerCore(ServerHandle* _serverHandle) :
    serverHandle(_serverHandle)
{
    oatpp::base::Environment::init();
}

ServerCore::~ServerCore()
{
    oatpp::base::Environment::destroy();
}

void ServerCore::StopServer()
{
    if(server!=nullptr)
        server->stop();
}

void ServerCore::operator()()
{
    /* Register Components in scope of run() method */
    AppComponent component(serverHandle);

    /* Get router component */
    OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router);

    /* Create MyController and add all of its endpoints to router */
    router->addController(std::make_shared<ServerController>(serverHandle));

    /* Get connection handler component */
    OATPP_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, connectionHandler, "http");

    /* Get connection provider component */
    OATPP_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, connectionProvider);

    /* Create server which takes provided TCP connections and passes them to HTTP connection handler */
    server.reset(new oatpp::network::Server(connectionProvider,connectionHandler));

    /* Priny info about server port */
    OATPP_LOGI("MyApp", "Server running on port %s", connectionProvider->getProperty("port").getData());

    /* Run server */
    server->run();
}